<template>
  <el-dialog
    v-model="visible"
    title="全局参数"
    width="600px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleClose"
  >
    <div class="global-param-container">
      <!-- 工具栏 -->
      <div class="toolbar">
        <el-button type="primary" @click="addParam">
          添加参数
        </el-button>
      </div>

      <!-- 参数表格 -->
      <el-table
        ref="table"
        :data="paramList"
        style="width: 100%"
        max-height="300"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="identifier" label="参数标识符" min-width="200">
          <template #default="{ row }">
            <el-input
              v-model="row.csbsf"
              placeholder="请输入参数标识符"
              clearable
            />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="参数名称" min-width="200">
          <template #default="{ row }">
            <el-input
              v-model="row.csmc"
              placeholder="请输入参数名称"
              clearable
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" >
          <template #default="{ $index }">
            <el-button
              type="danger"
              link
              size="small"
              @click="removeParam($index)"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script>
import { Delete } from '@element-plus/icons-vue'

export default {
  name: 'GlobalParamDialog',
  components: {
    Delete
  },
  props: {
    modelValue: {
      type: Boolean,
      default: false
    },
    selectedParam: {
      type: String,
      default: ''
    },
    global: {
      type: Object,
      default: () => ({})
    }
  },
  emits: ['update:modelValue', 'select'],
  data() {
    return {
      visible: false,
      saving: false,
      selectedRows: [],
      paramList: [
        { csbsf: '', csmc: '' }
      ]
    }
  },
  watch: {
    modelValue(val) {
      this.visible = val
      if (val) {
        this.initParamList()
      } else {
        // 弹窗关闭时重置状态
        this.resetDialog()
      }
    },
    visible(val) {
      this.$emit('update:modelValue', val)
    },
  },
  methods: {
    initParamList() {
      // 初始化参数列表，可以从API获取或使用默认值
      this.paramList = [
        { csbsf: '', csmc: '' }
      ]
      if (this.global !== null){
        this.paramList = this.global
      }
      // 如果有选中的参数，标记为选中
      if (this.selectedParam) {
        const selectedIndex = this.paramList.findIndex(p => p.csbsf === this.selectedParam)
        if (selectedIndex !== -1) {
          // 在下一个tick中设置选中状态
          this.$nextTick(() => {
            this.$refs.table?.toggleRowSelection(this.paramList[selectedIndex], true)
          })
        }
      }
    },
    
    addParam() {
      this.paramList.push({ csbsf: '', csmc: '' })
    },
    
    removeParam(index) {
      this.paramList.splice(index, 1)
    },
    
    handleSelectionChange(selection) {
      if (selection.length > 1) {
        // 取消第一个选中的
        const firstSelected = selection[0]
        this.$refs.table.toggleRowSelection(firstSelected, false)
        // 只保留最后一个
        this.selectedRows = [selection[selection.length - 1]]
      } else {
        this.selectedRows = selection
      }
    },
    
    handleClose() {
      this.visible = false
      this.resetDialog()
    },
    
    resetDialog() {
      // 重置弹窗状态
      this.selectedRows = []
      this.paramList = [{ csbsf: '', csmc: '' }]
      this.saving = false
    },
    
    handleSave() {
      // 获取选中的参数
      if (this.selectedRows.length === 0) {
        this.$message.warning('请至少选择一个参数')
        return
      }else if (this.selectedRows.length > 1){
        this.$message.warning('只能选择一个参数')
        return
      }
      
      // 验证参数完整性
      const invalidParams = this.paramList.filter(param => 
        param.csbsf.trim() === '' || param.csmc.trim() === ''
      )
      
      if (invalidParams.length > 0) {
        this.$message.error('请完善所有参数的标识符和名称')
        return
      }
      
      this.saving = true
      try {
        // 这里可以调用API保存全局参数
        this.$emit('select', {param:this.selectedRows,globalParam:this.paramList})
        this.visible = false
        this.resetDialog()
        this.$message.success('保存成功')
      } catch (error) {
        this.$message.error('保存失败，请重试')
      } finally {
        this.saving = false
      }
    }
  }
}
</script>

<style scoped>
.global-param-container {
  max-height: 400px;
}

.toolbar {
  margin-bottom: 16px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-input__wrapper) {
  box-shadow: none;
  border: 1px solid #DCDFE6;
}

:deep(.el-input__wrapper:hover) {
  border-color: #C0C4CC;
}

:deep(.el-input__wrapper.is-focus) {
  border-color: #409EFF;
}

:deep(.el-table) {
  border: 1px solid #EBEEF5;
}

:deep(.el-table th) {
  background-color: #F5F7FA;
  color: #606266;
  font-weight: 500;
}
</style> 